# coding: utf-8
from qeventmanager import qevent_manager

from common.server import BananaServer
from components import GridScrollArea, VideoCard, Alert
from ..tools import check_result


class SearchWidget(GridScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.search_keyword = ''
        self.verticalScrollBar().valueChanged.connect(self.onScroll)

    def search(self, keyword: str):
        self.search_keyword = keyword
        qevent_manager.addTask(BananaServer.search, keyword, self.currentPage, slot=self.onSearchResult)

    def onSearchResult(self, result: dict):
        data = check_result(result)
        if data is False:
            return
        vodrows = data.get('vodrows', [])
        self.totalPages = data.get('pageinfo', {}).get('totalpage', 0)
        if not vodrows:
            Alert.info('没有找到相关视频')
            return
        for vod in vodrows:
            if vod.get('isvip') != '0':
                continue
            card = VideoCard(self)
            card.setData(vod)
            self.addWidget(card)

        if self.count() < 20:
            self.nextPage()

    def nextPage(self):
        super().nextPage()
        self.search(self.search_keyword)
